package servlets;

import beans.SessionScopeBean;
import hibernate.Bean;
import hibernate.HibernateOperations;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/**
 * Created with IntelliJ IDEA.
 * User: shprotik
 * Date: 05.04.12
 * Time: 0:27
 * To change this template use File | Settings | File Templates.
 */
public class SaveServlet extends HttpServlet {

    public void init(ServletConfig config) throws ServletException {
        super.init(config);

    }


    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {

        SessionScopeBean value = new SessionScopeBean();
        HibernateOperations obj = new HibernateOperations();
        if(req.getParameter("fname")!=null)
        {obj.insert(req.getParameter("fname"), req.getParameter("sname"), req.getParameter("lname"));}

        List<Bean> inf =  obj.getAll();

        for (int i = 0; i < inf.size(); i++) {
            Bean tmp = inf.get(i);
            SessionScopeBean.Inner element = value.getElement();
            element.setName(tmp.getFirstName());
            element.setSecondName(tmp.getSecondName());
            element.setSurname(tmp.getLastName());
            element.setId(tmp.getId());
            value.getList().add(i, element);


        }
        req.getSession().setAttribute("collection",value);
        String url = "/task4/jsp/show.jsp";
        res.sendRedirect(res.encodeRedirectURL(url));
    }
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {

        SessionScopeBean value = new SessionScopeBean();
        HibernateOperations obj = new HibernateOperations();
        List<Bean> inf =  obj.getAll();
        for (int i = 0; i < inf.size(); i++) {
            Bean tmp = inf.get(i);
            SessionScopeBean.Inner element = value.getElement();
            element.setName(tmp.getFirstName());
            element.setSecondName(tmp.getSecondName());
            element.setSurname(tmp.getLastName());
            element.setId(tmp.getId());
            value.getList().add(i, element);


        }
        req.getSession().setAttribute("collection",value);
        String url = "/task4/jsp/show.jsp";
        res.sendRedirect(res.encodeRedirectURL(url));
    }
}